package behavioral_pattern.observer_pattern;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

/**
 * @version: 1.0
 * @Description: 观察者模式
 * @author: zZmH
 * @date: 2020/12/07 18:40
 */


public class ObserverPattern {
    public static void main(String[] args) {
        OilFutures oilFutures = new OilFutures();
        oilFutures.setPrice(12f);
        oilFutures.addObserver(new Bull());
        oilFutures.setPrice(13.5f);

    }
}
//具体目标类：原油期货
class OilFutures  extends Observable {
    private float price;
    public float getPrice() {
        return price;
    }

    public void setPrice(float price) {
        super.setChanged();
        super.notifyObservers(price);
        this.price = price;
    }

    @Override
    public String toString() {
        return "OilFutures{" +
                "price=" + price +
                "} " + super.toString();
    }
}
//具体观察者类：多方
class Bull implements Observer {
    public void update(Observable o, Object arg) {
        System.out.println(o);
        Float price = ((Float) arg).floatValue();
        if (price > 0) {
            System.out.println("油价上涨" + price + "元，多方高兴了！");
        } else {
            System.out.println("油价下跌" + (-price) + "元，多方伤心了！");
        }
    }
}
